//
//  JXHEmoticonController.swift
//  emojeTest
//
//  Created by juxiaohui on 16/10/31.
//  Copyright © 2016年 juxiaohui. All rights reserved.
//

import UIKit

let EmoticonCell = "EmoticonCell"


class JXHEmoticonController: UIViewController {

    // MARK: - LazyLoad
    
    lazy var manager = JXHEmoticonManager()
    lazy var collectionView : UICollectionView = UICollectionView.init(frame: CGRect.init(), collectionViewLayout: JXHEmotionCollectionViewLayout.init())
    
    lazy var toolBar : UIToolbar = UIToolbar.init()
    
    var emoticonCallBack : (_ emoticon : JXHEmoticon) -> ()
    
    init(emoticonCallBack : @escaping (_ emoticon : JXHEmoticon) -> ()) {
        
        self.emoticonCallBack = emoticonCallBack
        
        super.init(nibName: nil, bundle: nil)
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        
    }
}

// MARK: - UI界面相关
extension JXHEmoticonController {

    func setupUI() {
        
        view.addSubview(collectionView)
        view.addSubview(toolBar)
    
        toolBar.snp.makeConstraints { (make) in
            make.left.equalTo(view)
            make.right.equalTo(view)
            make.bottom.equalTo(view)
        }
        
        collectionView.snp.makeConstraints { (make) in
            make.top.equalTo(view)
            make.left.equalTo(view)
            make.right.equalTo(view)
            make.bottom.equalTo(toolBar.snp.top)
        }
        
        setupCollectionView()
        setupToolbar()
        
    }
    
    func setupCollectionView() {
        
        collectionView.backgroundColor = UIColor.white
        collectionView.register(JXHEmoticonCell.self, forCellWithReuseIdentifier: EmoticonCell)
        collectionView.dataSource = self
        collectionView.delegate = self
        collectionView.isPagingEnabled = true
        collectionView.showsVerticalScrollIndicator = false
        collectionView.showsHorizontalScrollIndicator = false
    }
    
    func setupToolbar()  {
        
        let titles = ["最近","默认","emoji","浪小花"]
        var index = 0
        var items = [UIBarButtonItem]()
    
        for title in titles {
            let item = UIBarButtonItem.init(title: title, style: .plain, target: self, action: #selector(JXHEmoticonController.itemClick(item:)))
            
            item.tag = index
            index += 1
            items.append(item)
            items.append(UIBarButtonItem.init(barButtonSystemItem: .flexibleSpace, target: nil, action: nil))
        }
        items.removeLast()
        toolBar.items = items
        toolBar.tintColor = UIColor.orange
    }
}

// MARK: - 时间监听

extension JXHEmoticonController {

    func itemClick(item : UIBarButtonItem){
        print(item.tag)
        let tag = item.tag
        
        let indexPath = IndexPath.init(item: 0, section: tag)
        collectionView.scrollToItem(at: indexPath, at: .left, animated: true)
    }
}


extension JXHEmoticonController : UICollectionViewDataSource,UICollectionViewDelegate {

    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        
        return manager.packages.count
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        let package = manager.packages[section]
        
        return package.emoticons.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: EmoticonCell, for: indexPath) as! JXHEmoticonCell
        
        let package = manager.packages[indexPath.section]
        
        let emoticon = package.emoticons[indexPath.item]
        
        cell.emoticon = emoticon

        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        let package = manager.packages[indexPath.section]
        
        let emoticon = package.emoticons[indexPath.item]

        //插入到最近表情
        insertResentlyEmoticon(emoticon: emoticon)
        
        //将表情回调出去
        emoticonCallBack(emoticon)
    }
    
    func insertResentlyEmoticon(emoticon : JXHEmoticon) {
        //删除和空白不需要添加
        if emoticon.isEmpty || emoticon.isRemove {
            return
        }
        
        //先删除一个表情
        if manager.packages.first!.emoticons.contains(emoticon) {//原来有这个表情
            
            let index = (manager.packages.first?.emoticons.index(of: emoticon))!
            
            manager.packages.first!.emoticons.remove(at: index)
            
        }else{//原来没有这个表情
            manager.packages.first!.emoticons.remove(at: 19)
        }
        
        manager.packages.first?.emoticons.insert(emoticon, at: 0)
    }
}

class JXHEmotionCollectionViewLayout: UICollectionViewFlowLayout {
    
    override func prepare() {
        super.prepare()
        
        let itemWH = UIScreen.main.bounds.width / 7
        itemSize = CGSize.init(width: itemWH, height: itemWH)
        minimumLineSpacing = 0
        minimumInteritemSpacing = 0
        scrollDirection = .horizontal
    }
}









